// Package database @program: account
//@author: edte
//@create: 2021-12-28 11:21
package database

import (
	log2 "account/log"
	"account/tools"
	"context"
	"fmt"
	"strconv"

	"errors"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func UserUpdateDb(user tools.User) error {
	mysqlPath := tools.GetEnv("MYSQL_PATH", "localhost:3306")
	mysqlUser := tools.GetEnv("MYSQL_USER", "root")
	mysqlPassword := tools.GetEnv("MYSQL_PASSWORD", "123456")
	db, err := gorm.Open(mysql.Open(mysqlUser+":"+mysqlPassword+"@tcp("+mysqlPath+")/users?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})

	// db, err := gorm.Open(mysql.Open("root:123456@tcp(localhost:3306)/users?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{})
	if err != nil {
		writeLog, err2 := log2.WriteLog(context.Background(), "account", "UserUpdateDb", strconv.Itoa(user.Id), "Error", "failed to connect database")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return errors.New("failed to connect database")
	}
	tmpUser := tools.User{}
	db.Model(&tools.User{}).Where("id = ?", user.Id).First(&tmpUser)
	if tmpUser.Id == 0 {
		writeLog, err2 := log2.WriteLog(context.Background(), "account", "UserUpdateDb", strconv.Itoa(user.Id), "Error", "Account does not exist.")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return errors.New("account does not exist")
	}
	if user.Password != "" {
		tmpUser.Password = user.Password
	}
	if user.EmailNumber != "" {
		tmpUser.EmailNumber = user.EmailNumber
	}
	if user.NickName != "" {
		tmpUser.NickName = user.NickName
	}
	db.Model(&tools.User{}).Where("id=?", tmpUser.Id).Updates(&tmpUser)
	return err
}
